﻿using FineUICore;

using System;
using System.Collections.Generic;
using System.Linq;
using BoYuanCore.DBServices.Base;
using BoYuanCore.Framework;
using BoYuanCore.Framework.MemoryCache;
using BoYuanCore.Framework.Net;
using BoYuanCore.WebUI.Code.Filter;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;

namespace BoYuanCore.Web.Areas.Admin.Controllers
{
    [Area("Admin")]
    [AuthorizationFilter]
    public partial class SysAdminController : BaseController
    {
        private readonly ILogger<SysAdminController> _logger;
        private readonly ICachingProvider _iCachingProvider;

        public SysAdminController(ILogger<SysAdminController> logger, ICachingProvider iCachingProvider) : base(logger)
        {
            _logger = logger;
            _iCachingProvider = iCachingProvider;
        }

        #region ListPage
        // GET: Admin/SysAdmin
        public ActionResult Index()
        {
            var list= DB.Select<Entities.SysRole>().Where(p => p.IsDel == false).ToList(p => new { p.RoleName, GridID= p.ID.ToString() });
            list.Insert(0,new {RoleName="全部",GridID="%"});
            ViewBag.role = list;

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ShowGrid(IFormCollection fc)
        {
            var grid1 = UIHelper.Grid("Grid1"); 
            long recordCount = 0;
            int pageSize = int.Parse(fc["ddlPageSize"]);
            string keyword = fc["txb_keyword"].ToString().Trim();
            //此处代码不能设置断点debug。
            var dataList = DB.Select<Entities.SysAdmin,Entities.SysRole>()
                .LeftJoin((a,r)=>a.RoleID==r.ID)
                .WhereIf(keyword.Length > 0, (a, r) => a.RealName.Contains(keyword) || a.LoginName.Contains(keyword))
                .WhereIf(long.TryParse(fc["f_RoleID"].ToString(),out var roleResult), (a, r) => a.RoleID==roleResult)
                .OrderBy((a, r) => a.ID)
                .Count(out recordCount).Page(int.Parse(fc[grid1.Source.ID + "_pageIndex"]) + 1, pageSize)
                .ToList((a, r)=>new Models.SysAdminVM());

            grid1.DataSource(dataList, fc[grid1.Source.ID + "_fields[]"].ToString().Split(','));
            grid1.RecordCount((int)recordCount);
            grid1.PageSize(pageSize);

            return UIHelper.Result();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Button_delete_Click(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids))
            {
                NotifyQuestion("请选择要删除的选中行！");
            }
            else
            {
                var tempStrs = ids.Substring(1).Split(',');
                List<long> idList = new List<long>();
                foreach (var str in tempStrs)
                {
                    if (long.TryParse(str.Trim(), out var idResult) && idResult != 1)//排除删除默认管理员
                    {
                        idList.Add(idResult);
                    }
                }
                if (idList.Count == 0)
                {
                    NotifyQuestion("请选择要删除的选中行！");
                }
                else
                {
                    DB.Delete<Entities.SysAdmin>().Where(p => idList.Contains(p.ID)).ExecuteAffrows();
                    foreach (var id in idList)
                    {
                        DBServices.SysAdmin.RemoveCache(id, _iCachingProvider);//更新缓存
                    }
                    AlertSuccess("删除成功！", false, "onGridBind()");
                }
            }
            return UIHelper.Result();
        }
        #endregion

        #region AddPage

        public ActionResult Add()
        {
            ViewBag.role = DB.Select<Entities.SysRole>().Where(p => p.IsDel == false).ToList(p=>new {p.RoleName, GridID = p.ID.ToString()});

            if (long.TryParse(Request.Query["id"], out long id))//编辑页面初始化
            {
                Entities.SysAdmin mo = DBServices.SysAdmin.GetAdminByCache(id, _iCachingProvider); ;
                ViewBag.haveUpdate = 1;
                return View(mo);
            }
            return View();//添加页面
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Button_save_OnClick(IFormCollection fc)
        {
            bool isEdit = long.TryParse(fc["f_ID"], out long ID);
            if (!isEdit) //添加
            {
                if (string.IsNullOrEmpty(fc["f_Password"]))
                {
                    NotifyQuestion("请设置密码!");
                    return UIHelper.Result();
                }
            }

            bool haveLoginName = DB.Select<Entities.SysAdmin>()
                .WhereIf(isEdit,p=>p.ID!=ID)
                .Where(p => p.LoginName == fc["f_LoginName"]).Any();
            if (haveLoginName)
            {
                NotifyError("登录名称重复请换个！");
                return UIHelper.Result();
            }

            Entities.SysAdmin mo = new Entities.SysAdmin();
            mo.LoginName = fc["f_LoginName"];
            mo.RealName = fc["f_RealName"];
            if (long.TryParse(fc["f_RoleID"], out var RoleIDTempResult)) mo.RoleID = RoleIDTempResult;
            mo.Remark = fc["f_Remark"];
            mo.Photo =string.Empty;
            if (int.TryParse(fc["f_Sort"], out var SortTempResult)) mo.Sort = SortTempResult;
            mo.IsDel = Convert.ToBoolean(fc["f_IsDel"]);

            if (!isEdit)//添加
            {
                mo.Password = Security.MD5Helper.GetMd5Pwd(fc["f_Password"]);

                if (FreeSqlHelper.InsertModel(mo) > 0)
                {
                    AlertInfor("添加成功", true);
                }
                else
                {
                    NotifyError("添加失败");
                }
            }
            else//修改
            {
                mo.ID = ID;
                int returnNum = 0;

                if (string.IsNullOrEmpty(fc["f_Password"]))
                {
                    returnNum = FreeSqlHelper.UpdateModels(mo,
                        p => new { p.LoginName, p.RealName, p.RoleID, p.Remark, p.Photo, p.Sort, p.IsDel });
                }
                else //更改密码
                {
                    mo.Password = Security.MD5Helper.GetMd5Pwd(fc["f_Password"]);
                    returnNum = FreeSqlHelper.UpdateModels(mo,
                        p => new { p.LoginName, p.RealName, p.RoleID,p.Password, p.Remark, p.Photo, p.Sort, p.IsDel });
                }

                if (returnNum > 0)
                {
                    DBServices.SysAdmin.RemoveCache(mo.ID, _iCachingProvider);//更新缓存
                    AlertInfor("修改成功", true);
                }
                else
                {
                    NotifyError("修改失败");
                }
            }
            return UIHelper.Result();
        }

        #endregion
    }
}
